﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HomeWork
{
    internal class ArticleRepository : IRepository<Article>
    {
        DateTime xyarticleTime = new DateTime(2019, 4, 21); // 小鱼文章的创建时间
        public IList<Article> GetArticlesByAuthorFeiGe()
        {
            return entities.Where(a => a.Author != null && a.Author.Name == "飞哥").ToList();
        }

        public IList<Article> GetArticlesByAuthorxy()
        {
            return entities.Where(a => a.Author != null && a.Author.Name == "小鱼" && a.CreateTime < xyarticleTime).ToList();
        }

        public IList<Article> OrderbyTime()
        {
            return entities.OrderBy(a => a.CreateTime).ToList();
        }

        public IList<Article> OrderbyDescend()
        {
            return entities.OrderByDescending(a => a.CreateTime).ToList();
        }

        public IEnumerable<IGrouping<User, Article>> GroupByAuthor()
        {
            return entities.GroupBy(s => s.Author);
        }

        public IList<Article> GetArticlesKeyword()
        {
            return entities.Where(a => a.KeyWords != null &&
                      a.KeyWords.Any(kw => kw.Text != null && kw.Text.Contains("c#") || kw.Text.Contains(".net", StringComparison.OrdinalIgnoreCase))).ToList();
        }

        public IList<Article> GetArticlesCountMost()
        {
            //var maxCount = entities.Max(a => a.Comments != null ? a.Comments.Count : 0);
            var maxCount = entities.Max(a => a.Comments?.Count ?? 0);//优化版
            return entities.Where(a => a.Comments != null && a.Comments.Count == maxCount).ToList();
        }

        public IEnumerable<Article> ArticlesComentMostGroup()
        {
            var authors = entities.GroupBy(s => s.Author);
              //authors.Select(a=> a.OrderByDescending(a => a.Comments != null ? a.Comments.Count : 0));

            var result = authors.Select(g =>
            {
                // 在每组内找出评论数最多的文章
                return g.OrderByDescending(a => a.Comments?.Count ?? 0).FirstOrDefault();
            });

            return result;
        }

        public IEnumerable<Article> RecentArticlesByAuthor()
        {
            var authors = entities.GroupBy(s => s.Author);
            var result = authors.Select(g =>
            {
                //找出每个作者最近发布的一篇文章 
                return g.OrderByDescending(a => a.CreateTime).FirstOrDefault();
            });

            return result;
        }

    }
}
